package com.teacher.mobile.controller;


import com.teacher.common.CommonResult;
import com.teacher.pojo.vo.permission.PermissionTreeVo;
import com.teacher.security.entity.permission.Permission;
import com.teacher.service.IPermissionService;
import com.teacher.pojo.vo.permission.PermissionAddVo;
import com.teacher.pojo.vo.permission.PermissionUpdateVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zfm
 * @since 2021-06-15
 */
@RestController
@RequestMapping("/pc/permission")
public class PermissionController {
    @Autowired
    private IPermissionService iPermissionService;

    /**
     * @param permissionAddVo object of permission's value
     * @return add permission whether success
     */
    @PostMapping
    @ApiOperation("添加权限")
    @PreAuthorize("hasAuthority('menu_add')")
    public CommonResult<String> addPermission(@RequestBody PermissionAddVo permissionAddVo) {
        return iPermissionService.addPermission(permissionAddVo);
    }

    /**
     * @param permissionUpdateVo object of permission's value
     * @return update permission whether success
     */
    @PutMapping
    @ApiOperation("更新权限")
    @PreAuthorize("hasAuthority('menu_update')")
    public CommonResult<String> updatePermission(@RequestBody PermissionUpdateVo permissionUpdateVo) {
        return iPermissionService.updatePermission(permissionUpdateVo);
    }

    /**
     * query all permission by tree's shape
     *
     * @return permission by tree's shape
     */
    @GetMapping
    @ApiOperation("查询所有权限")
    @PreAuthorize("hasAuthority('menu_get')")
    public CommonResult<List<PermissionTreeVo>> getTreePermission() {
        return iPermissionService.treePermission();
    }

    /**
     * delete permission
     *
     * @param ids delete permission's ids
     * @return delete whether success
     */
    @DeleteMapping
    @ApiOperation("删除权限")
    @PreAuthorize("hasAuthority('menu_delete')")
    public CommonResult<String> deletePermission(@RequestBody List<Long> ids) {
        if (iPermissionService.removeByIds(ids)) {
            return CommonResult.success("删除成功");
        }
        return CommonResult.failed("删除失败");
    }

    /**
     * get permission by role's id
     *
     * @param id
     * @return
     */
    @GetMapping("/{roleId}")
    @ApiOperation("查询角色权限")
    @PreAuthorize("hasAuthority('menu_get')")
    public CommonResult<List<String>> getPermissionByRoleId(@PathVariable("roleId") Long id) {
        return iPermissionService.getPermissionByRoleId(id);
    }

    /**
     * get menu of root
     *
     * @return
     */
    @GetMapping("/root")
    @ApiOperation("获取root菜单")
    public CommonResult<List<Permission>> getRootMenu() {
        return iPermissionService.getRootMenu();
    }
}

